package com.ruoyi.door.controller.app.orderinfo;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.door.controller.app.orderinfo.vo.AppOrderInfoCreateReqVO;
import com.ruoyi.door.controller.app.orderinfo.vo.AppOrderRefundReqVO;
import com.ruoyi.door.domain.PayLog;
import com.ruoyi.door.service.DoorOrderRefundService;
import com.ruoyi.door.service.DoorOrderService;
import com.ruoyi.door.utils.baofu.BaoFuConstants;
import com.ruoyi.door.utils.baofu.BaofuUtil;
import com.ruoyi.door.utils.baofu.rsa.RsaCodingUtil;
import com.ruoyi.door.utils.baofu.rsa.SignatureUtils;
import com.ruoyi.door.utils.baofu.util.FormatUtil;
import com.ruoyi.door.utils.baofu.util.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "APP 订单退款", tags = "APP 订单退款")
@RestController
@Slf4j
@RequestMapping("/app-api/door/order-refund")
public class AppDoorOrderRefundController {

    @Autowired
    private DoorOrderRefundService doorOrderRefundService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private DoorOrderService doorOrderService;
    @Autowired
    private EasyEntityQuery easyEntityQuery;

    public String getResourcePath(String resourcePath) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + resourcePath);
        File file = resource.getFile();
        return file.getAbsolutePath();
    }

    @ApiOperation("提交退款")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    @Anonymous
    public AjaxResult add(@Validated @RequestBody AppOrderRefundReqVO reqVO) {
        doorOrderRefundService.submit(reqVO);
        return AjaxResult.success();
    }

    @ApiOperation("建行退款回调")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/callback-bank")
    @Anonymous
    public String refundCallbackBank(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取所有请求参数并转换为字符串
        // 读取 InputStream 的内容为字符串
//        StringBuilder requestBody = new StringBuilder();
//        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
//            String line;
//            while ((line = reader.readLine()) != null) {
//                requestBody.append(line).append("\n");
//            }
//        }
        Map<String, String> formMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            // 假设每个字段只有一个值
            formMap.put(entry.getKey(), entry.getValue()[0]);
        }
        String uuid = IdUtil.fastUUID();
        //插入日志
        PayLog payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("formMap");
        payLog.setRequestBody(JSONObject.toJSONString(formMap));
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        log.info("退款协议回调进来了: formMap={}", JSONObject.toJSONString(formMap));


        String requestBody = formMap.get("data_content");
        //插入日志
        payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("data_content");
        payLog.setRequestBody(requestBody);
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();

        //解密
        String cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);
        String DeCodeResult = RsaCodingUtil.decryptByPubCerFile(requestBody.toString(), cerpath);
        String Base64Dec = SecurityUtil.Base64Decode(DeCodeResult);
        log.info("退款协议回调进来了: 解密后={}", Base64Dec);
        //插入日志
        payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("Base64Dec");
        payLog.setRequestBody(Base64Dec);
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();

        JSONObject jsonObject = JSONObject.parseObject(Base64Dec);
        if (!jsonObject.containsKey("resp_code")) {
            throw new Exception("缺少resp_code参数！");
        }
        if (jsonObject.get("resp_code").toString().equals("S")) {
            log.info("退款成功！");
            String refund_order_no = request.getParameter("refund_order_no");//退款商户订单号
            String refund_amt = request.getParameter("refund_amt");//退款成功金额

            doorOrderService.refundCallBack(refund_order_no);
        }
        return "OK";

    }


    @ApiOperation("微信退款回调")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/callback-jh")
    @Anonymous
    public String refundCallbackJh(@RequestBody String jsonBody, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //聚合的要验签
        // 获取所有请求参数并转换为字符串
        Map<String, String> formMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            // 假设每个字段只有一个值
            formMap.put(entry.getKey(), entry.getValue()[0]);
        }
        String uuid = IdUtil.fastUUID();

        //插入日志
        PayLog payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("聚合支付退款:formMap");
        payLog.setRequestBody(JSONObject.toJSONString(formMap));
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        // 记录日志
        log.info("退款聚合回调进来了: formMap={}", JSONObject.toJSONString(formMap));

//        if (!formMap.containsKey("signature")) {
//            throw new Exception("缺少验签参数！");
//        }
        String RSign = formMap.get("signStr");
        String dataContent = formMap.get("dataContent");
        log.info("返回的验签值：" + RSign);
        log.info("返回的dataContent：" + dataContent);
        payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("聚合支付退款:dataContent");
        payLog.setRequestBody(dataContent);
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        JSONObject jsonObject = JSONObject.parseObject(dataContent);
        String resultCode = jsonObject.getString("resultCode");
        String tradeNo = jsonObject.getString("tradeNo");
        String outTradeNo = jsonObject.getString("outTradeNo");
        log.info("返回的resultCode：" + resultCode);
        log.info("返回的tradeNo：" + tradeNo);
        log.info("返回的outTradeNo：" + outTradeNo);

        if (resultCode.equals("SUCCESS")) {
            log.info("支付成功！");
            doorOrderService.refundCallBack(outTradeNo);
        }
        String cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

//        if (SignatureUtils.verifySignature(cerpath, dataContent, RSign)) {
//            log.info("验签：Yes");//验签成功
//
//            if (!formMap.containsKey("resultCode")) {
//                throw new Exception("缺少resultCode参数！");
//            }
//            if (formMap.get("resultCode").toString().equals("SUCCESS")) {
//                log.info("退款成功！");
//
//                String tradeNo = request.getParameter("tradeNo");//与商户退款订单号对应的宝付侧唯一退款订单号
//                String outTradeNo = request.getParameter("outTradeNo");//商户推订单号
//                doorOrderService.refundCallBack(outTradeNo);
//            }
//        } else {
//            log.info("验签：NO");
//        }


        return "OK";
    }

    public static void main(String[] args) {

    }

}